package com.ym.wcp.framework.utils;

import com.ym.wcp.framework.exception.BizException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Base64Utils;


public class PasswordUtil {
    private static final PasswordEncoder passwordEncoder;

    static {
        passwordEncoder = new BCryptPasswordEncoder();
    }

    public static String encodeOriginal(String pwd) {
        return passwordEncoder.encode(pwd);
    }

    public static String encodeBCrypt(String pwdBase64FromClient) {
        try {
            if (!Base64.isBase64(Base64Utils.decodeFromString(pwdBase64FromClient))) {
                throw new BizException("密码未Base64加密，请确认");
            }
            return passwordEncoder.encode(new String(Base64Utils.decodeFromString(pwdBase64FromClient)));
        } catch (Exception e) {
            throw new BizException("密码未Base64加密，请确认");
        }
    }

    public static boolean matches(String originalPwd, String encryptPwd) {
        return passwordEncoder.matches(originalPwd, encryptPwd);
    }
}
